package com.dev.dream.exochatlockscreen;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.AssetFileDescriptor;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.AlarmClock;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v4.view.GestureDetectorCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dev.dream.exochatlockscreen.adapter.AppToolbarAdapter;
import com.dev.dream.exochatlockscreen.adapter.NotifiExoAdapter;
import com.dev.dream.exochatlockscreen.battery.BatteryInfo;
import com.dev.dream.exochatlockscreen.homelocker.HomeKeyLocker;
import com.dev.dream.exochatlockscreen.model.AppToolbarItem;
import com.dev.dream.exochatlockscreen.model.NotifiItem;
import com.dev.dream.exochatlockscreen.service.SLockscreen;
import com.dev.dream.exochatlockscreen.service.ServiceFlashlight;
import com.dev.dream.libs.listviewanimation.simple.SwingBottomInAnimationAdapter;
import com.dev.dream.libs.preperences.DevDreamPreferenceManager;
import com.dev.dream.libs.share.MyShare;
import com.dev.dream.libs.slidemenu.circleimageview.AWCircleImageView;
import com.dev.dream.libs.slidemenu.utils.MathuUntil;
import com.rockerhieu.emojicon.EmojiconTextView;

@SuppressLint("NewApi")
public class LockScreenAppActivity extends Activity {

	DevDreamPreferenceManager s5KeypadPreferences;
	// public static final String PREFERENCE_NAME =
	// "istudio.app.s5keypadlockscreen";

	String MONTH[] = new String[] { "January", "February", "March", "April",
			"May", "June", "July", "August", "September", "October",
			"November", "December" };

	String DAY_OF_WEEK[] = new String[] { "Sunday", "Monday", "Tuesday",
			"Wednesday", "Thursday", "Friday", "Saturday", "" };

	public static boolean CREATE = false;
	KeyguardManager.KeyguardLock k1;

	private HomeKeyLocker mHomeKeyLocker;

	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		// this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);

		this.getWindow().setType(
				WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
						| WindowManager.LayoutParams.FLAG_FULLSCREEN
						| WindowManager.LayoutParams.TYPE_KEYGUARD
						| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);

		super.onAttachedToWindow();
	}

	private static View gameView;
	RelativeLayout layoutMain, layoutGame, layoutPin;
	LinearLayout llDateTime;

	Context mContext;

	TextView shimmerTime, shimmerDate, btnDelete, btnCancel;
	// Shimmer shimmer;

	// private Typeface mFace;

	ImageView btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0,
			btn_pin_1, btn_pin_2, btn_pin_3, btn_pin_4, imgPasswordFail;

	// NumberView tvSecond1, tvSecond2;
	int index_pin = 1;

	// Animation aFailPassword;
	Animation aSetPassword;
	Animation aDateTime, aToolbarImg, aToolbarViewIn, aToolbarViewOut,
			aRotationNotifi, aRotationCircle, aArrow1, aArrow2, aArrow3,
			aArrow4, aArrow5;

	BatteryInfo batteryInfo;
	TextView tvBattery, tvNetwork;

	ImageView imgToolBar;

	LinearLayout llToolbar;
	private int width, height;

	private GestureDetectorCompat mDetector;

	ListView lv_app_toolbar;
	private ArrayList<AppToolbarItem> appToolbarItems;
	AppToolbarAdapter appToolbarAdapter;
	private String[] name_app_toolbar;
	private TypedArray icon_app_toolbar;
	SwingBottomInAnimationAdapter swingBottomInAnimationAdapter;

	TextView tvSMS, tvMissCall;
	ImageView imgSMS;
	ListView lvNotifi;
	LinearLayout llSMS, llMissCall;

	// FrameLayoutWithBluredBackground frameBlur;

	@Override
	protected void attachBaseContext(Context newBase) {
		super.attachBaseContext(new CalligraphyContextWrapper(newBase));
	}

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		CalligraphyConfig.initDefault("fonts/ttt.ttf", R.attr.fontPath);
		SLockscreen.IS_RUN = true;
		// getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

		// try {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_FULLSCREEN
						| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);

		if (getIntent() != null && getIntent().hasExtra("kill")
				&& getIntent().getExtras().getInt("kill") == 1) {
			// Toast.makeText(this, "" + "kill activityy",
			// Toast.LENGTH_SHORT).show();

			finish();
		}

		// try {

		mContext = this;
		// detector = new SimpleGestureFilter(this, this);
		// initialize receiver

		// startService(new Intent(this, SLockscreen.class));

		setContentView(R.layout.lock_activity);

		s5KeypadPreferences = new DevDreamPreferenceManager(
				getApplicationContext(),
				EXOChatKeypadPreferences.getInstance().PREFERENCE_NAME);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		height = displaymetrics.heightPixels;
		width = displaymetrics.widthPixels;

		layoutMain = (RelativeLayout) findViewById(R.id.rLock);
		layoutGame = (RelativeLayout) findViewById(R.id.rGame);

		llDateTime = (LinearLayout) findViewById(R.id.llDateTime);
		layoutPin = (RelativeLayout) findViewById(R.id.rPin);
		// frameBlur = (FrameLayoutWithBluredBackground)
		// findViewById(R.id.frameBlur);
		llUnlock = (LinearLayout) findViewById(R.id.llUnlock);
		// tvSecond2 = (NumberView) findViewById(R.id.tvSecond2);
		// tvSecond1 = (NumberView) findViewById(R.id.tvSecond1);

		if (SLockscreen.instance != null) {
			if (SLockscreen.instance.isChangeBlurImage()) {
				SLockscreen.instance.changeBlurImage();
				SLockscreen.instance.setChangeBlurImage(false);

			}
		} else {
			startService(new Intent(getApplicationContext(), SLockscreen.class));
		}

		// layoutPin
		// .setBackgroundDrawable(SLockscreen.instance.backgroundBlur[EXOChatKeypadPreferences
		// .getInstance().getImgIndexBg()]);

		layoutPin.setVisibility(View.GONE);
		shimmerTime = (TextView) findViewById(R.id.stvTime);
		shimmerDate = (TextView) findViewById(R.id.stvDate);
		btnDelete = (TextView) findViewById(R.id.btnDelete);
		btnCancel = (TextView) findViewById(R.id.btnCancel);
		btn_pin_1 = (ImageView) findViewById(R.id.btn_pin_1);
		btn_pin_2 = (ImageView) findViewById(R.id.btn_pin_2);
		btn_pin_3 = (ImageView) findViewById(R.id.btn_pin_3);
		btn_pin_4 = (ImageView) findViewById(R.id.btn_pin_4);
		imgPasswordFail = (ImageView) findViewById(R.id.imgPasswordFail);
		imgPasswordFail.setVisibility(View.GONE);

		tvBattery = (TextView) findViewById(R.id.tvBattery);
		tvNetwork = (TextView) findViewById(R.id.tvNetwork);
		tvNetwork.setText(getNetwork());

		imgToolBar = (ImageView) findViewById(R.id.imgToolbar);
		imgToolBar.setVisibility(View.GONE);

		llToolbar = (LinearLayout) findViewById(R.id.llToolbar);
		llToolbar.setVisibility(View.GONE);

		lv_app_toolbar = (ListView) findViewById(R.id.lv_toolbar);

		name_app_toolbar = getResources().getStringArray(
				R.array.app_name_toolbar);
		icon_app_toolbar = getResources().obtainTypedArray(
				R.array.app_icon_toolbar);

		appToolbarItems = new ArrayList<AppToolbarItem>();
		for (int i = 0; i < name_app_toolbar.length; i++) {
			appToolbarItems.add(new AppToolbarItem(i, "", name_app_toolbar[i],
					icon_app_toolbar.getResourceId(i, -1), null));
		}

		appToolbarAdapter = new AppToolbarAdapter(getApplicationContext(),
				appToolbarItems, this);

		lv_app_toolbar.setAdapter(appToolbarAdapter);

		tvSMS = (TextView) findViewById(R.id.tv_sms);
		imgSMS = (ImageView) findViewById(R.id.imgSMS);
		lvNotifi = (ListView) findViewById(R.id.lv_notifi);
		llSMS = (LinearLayout) findViewById(R.id.llSMS);
		llSMS.setVisibility(View.GONE);

		tvMissCall = (TextView) findViewById(R.id.tv_miss_call);
		llMissCall = (LinearLayout) findViewById(R.id.llMissCall);

		lvNotifi.setVisibility(View.GONE);
		llMissCall.setVisibility(View.GONE);
		// aSetImgSms.setTarget(imgSMS);
		// aSetImgSms.start();

		// shimmer = new Shimmer();

		// shimmer.setDuration(500).setStartDelay(50)
		// .setDirection(Shimmer.ANIMATION_DIRECTION_LTR);

		// shimmer.setRepeatCount(0)
		// .setDuration(500)
		// .setStartDelay(300)
		// .setDirection(Shimmer.ANIMATION_DIRECTION_RTL)
		// .setAnimatorListener(new Animator.AnimatorListener(){});
		// shimmer.start(shimmerTime);
		// shimmer.start(shimmerDate);
		// shimmer.start(btnDelete);
		// shimmer.start(btnCancel);

		// mFace = Typeface.createFromAsset(mContext.getAssets(),
		// "fonts/ttt.ttf");
		// shimmerDate.setTypeface(mFace);
		// shimmerTime.setTypeface(mFace);
		// tvBattery.setTypeface(mFace);
		// tvNetwork.setTypeface(mFace);

		// RelativeLayout.LayoutParams param = new
		// RelativeLayout.LayoutParams(
		// RelativeLayout.LayoutParams.FILL_PARENT,
		// RelativeLayout.LayoutParams.FILL_PARENT);

		if (!EXOChatKeypadPreferences.getInstance().isDisplayDate()) {
			shimmerDate.setVisibility(View.GONE);

		}

		if (!EXOChatKeypadPreferences.getInstance().isDisplayTime()) {
			shimmerTime.setVisibility(View.GONE);
			// tvSecond1.setVisibility(View.GONE);
			// tvSecond2.setVisibility(View.GONE);
		}

		llDateTime.setVisibility(View.GONE);

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				input_passcode = "";
				index_pin = 1;
				btn_pin_1.setSelected(false);
				btn_pin_2.setSelected(false);
				btn_pin_3.setSelected(false);
				btn_pin_4.setSelected(false);
				type_finish = 0;
				layoutPin.setVisibility(View.GONE);
				valueBlur = 1;
				// frameBlur.setBlurRadius(valueBlur);
				llUnlock.setVisibility(View.VISIBLE);
				llDateTime.setVisibility(View.VISIBLE);
			}
		});

		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				deletePin();
			}
		});

		btn1 = (ImageView) findViewById(R.id.btn1);
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(1);
			}
		});

		btn2 = (ImageView) findViewById(R.id.btn2);
		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(2);
			}
		});

		btn3 = (ImageView) findViewById(R.id.btn3);
		btn3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(3);
			}
		});

		btn4 = (ImageView) findViewById(R.id.btn4);
		btn4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(4);
			}
		});

		btn5 = (ImageView) findViewById(R.id.btn5);
		btn5.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(5);
			}
		});

		btn6 = (ImageView) findViewById(R.id.btn6);
		btn6.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(6);
			}
		});

		btn7 = (ImageView) findViewById(R.id.btn7);
		btn7.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(7);
			}
		});

		btn8 = (ImageView) findViewById(R.id.btn8);
		btn8.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(8);
			}
		});

		btn9 = (ImageView) findViewById(R.id.btn9);
		btn9.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(9);
			}
		});

		btn0 = (ImageView) findViewById(R.id.btn0);
		btn0.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setPin(0);
			}
		});

		// setContentView(layout);

		// layout.setVisibility(View.GONE);

		CREATE = true;

		// } catch (Exception e) {
		// // TODO: handle exception
		// }

		mHomeKeyLocker = new HomeKeyLocker();
		mHomeKeyLocker.lock(this);

		if (EXOChatKeypadPreferences.getInstance().isVibrator()
				&& !EXOChatKeypadPreferences.getInstance().isEnableSaveMode()) {
			vibrator = (Vibrator) getApplicationContext().getSystemService(
					Context.VIBRATOR_SERVICE);
		}

		// aFailPassword =
		// AnimationUtils.loadAnimation(getApplicationContext(),
		// R.anim.fail_password);

		aSetPassword = AnimationUtils.loadAnimation(this, R.anim.fail_password);

		aDateTime = AnimationUtils.loadAnimation(this,
				R.anim.translate_datetime);
		aToolbarImg = AnimationUtils.loadAnimation(this,
				R.anim.translate_toolbar_img);
		aToolbarViewIn = AnimationUtils.loadAnimation(this,
				R.anim.translate_toolbar_view_in);
		aToolbarViewOut = AnimationUtils.loadAnimation(this,
				R.anim.translate_toolbar_view_out);

		aRotationNotifi = AnimationUtils.loadAnimation(this,
				R.anim.rotation_img_notifi);
		aRotationCircle = AnimationUtils.loadAnimation(this,
				R.anim.rotation_img_circle);

		if (EXOChatKeypadPreferences.getInstance().isSound()
				&& !EXOChatKeypadPreferences.getInstance().isEnableSaveMode()) {
			sUnlock = startSound("sound/sound_"
					+ EXOChatKeypadPreferences.getInstance().getIndexSound()
					+ ".mp3");
			// sTouch = startSound("sound/touch.ogg");
		}

		mDetector = new GestureDetectorCompat(this, new MyGestureListener());

		dialog.sendEmptyMessage(EXOChatKeypadPreferences.VISIBLE);

		msg = getResources().getStringArray(R.array.message_exo);

		tvMsg = (EmojiconTextView) findViewById(R.id.tv_msg);

		tvMsg.setTypeface(SLockscreen.fontMsg);

		imgIcon = (AWCircleImageView) findViewById(R.id.imgIcon);
		imgBg = (ImageView) findViewById(R.id.imgBg);

		if (EXOChatKeypadPreferences.getInstance().isRandomBg()) {
			int random = MathuUntil.random(1, EXOChatKeypadPreferences.size_bg);
			Bitmap bg = MyShare.getBitmapFromAssets(getApplicationContext(),
					"bg/" + random + ".jpg");
			imgBg.setImageBitmap(bg);

		} else {
			imgBg.setImageBitmap(SLockscreen.instance.background[EXOChatKeypadPreferences
					.getInstance().getImgIndexBg()]);
		}
		llMsg = (LinearLayout) findViewById(R.id.ll_msg);

		if (EXOChatKeypadPreferences.getInstance().isSendMsg()) {

			llMsg.setBackgroundResource(R.drawable.msgbox_self);

			if (EXOChatKeypadPreferences.getInstance().getUrlMyAvatar()
					.equals(EXOChatKeypadPreferences.DEFAULT_URL_MY_AVATAR)) {

				imgIcon.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.default_avatar));

			} else {

				if (!SLockscreen.loadMyAvatar) {
					SLockscreen.loadMyAvatar = true;
					SLockscreen.instance.loadMyAvatar();
				}
				imgIcon.setImageBitmap(SLockscreen.instance.bitmapMyAvatar);
			}

		} else {

			// android:background="@drawable/msgbox_other"

			llMsg.setBackgroundResource(R.drawable.msgbox_other);

			if (SLockscreen.instance.avatarIcon[EXOChatKeypadPreferences
					.getInstance().getIconExo()] != null) {
				imgIcon.setImageBitmap(SLockscreen.instance.avatarIcon[EXOChatKeypadPreferences
						.getInstance().getIconExo()]);
			} else {
				imgIcon.setImageBitmap(MyShare.getBitmapFromAssets(
						getApplicationContext(), "ic/"
								+ EXOChatKeypadPreferences.getInstance()
										.getIconExo() + ".jpg"));
			}
		}

		windowwidth = getWindowManager().getDefaultDisplay().getWidth();

		windowheight = getWindowManager().getDefaultDisplay().getHeight();

		// MarginLayoutParams marginParams2 = new MarginLayoutParams(
		// tvMsg.getLayoutParams());
		//
		// // marginParams2.setMargins((windowwidth / 24) * 10,
		// // ((windowheight / 32) * 8), 0, 0);
		//
		// //
		// marginParams2.setMargins(((windowwidth-droid.getWidth())/2),((windowheight/32)*8),0,0);
		// LinearLayout.LayoutParams layoutdroid = new
		// LinearLayout.LayoutParams(
		// marginParams2);
		//
		// tvMsg.setLayoutParams(layoutdroid);

		// imgIcon.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// // TODO Auto-generated method stub
		// imgIcon.startAnimation(aScaleNotifi);
		// }
		// });

		rIcon = (RelativeLayout) findViewById(R.id.rIcon);

		layoutParams = (LinearLayout.LayoutParams) rIcon.getLayoutParams();

		// frameBlur.setBlurRadius(1);

		imgIcon.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub

				switch (event.getAction()) {

				case MotionEvent.ACTION_DOWN:

					old_x = (int) event.getRawX();
					int[] hompos = new int[2];
					// int[] phonepos=new int[2];
					droidpos = new int[2];

					break;
				case MotionEvent.ACTION_MOVE:

					// if (EXOChatKeypadPreferences.getInstance()
					// .isEnablePasscode()) {
					// new_x = (int) event.getRawX();
					// if (new_x > old_x) {
					// if (valueBlur < 24) {
					// valueBlur++;
					// frameBlur.setBlurRadius(valueBlur);
					// }
					// } else {
					// if (valueBlur > 1) {
					// valueBlur--;
					// frameBlur.setBlurRadius(valueBlur);
					// }
					// }
					// }
					int x_cord = (int) event.getRawX() / 2;

					// int y_cord = (int) event.getRawY();

					// if(x_cord>windowwidth-(windowwidth/24)){x_cord=windowwidth-(windowwidth/24)*2;}
					// if(y_cord>windowheight-(windowheight/32)){y_cord=windowheight-(windowheight/32)*2;}

					layoutParams.leftMargin = x_cord;
					// layoutParams.topMargin = y_cord;

					tvMsg.getLocationOnScreen(droidpos);
					rIcon.setLayoutParams(layoutParams);

					break;
				case MotionEvent.ACTION_UP:

					int x_cord1 = (int) event.getRawX() / 2;
					// int y_cord2 = (int) event.getRawY();

					if (x_cord1 > windowwidth - 400) {
						layoutParams.leftMargin = 0;
						rIcon.setLayoutParams(layoutParams);
						if (EXOChatKeypadPreferences.getInstance().isFirst()) {
							EXOChatKeypadPreferences.getInstance().setFirst(
									false);
						}
						// kai

						dialog.sendEmptyMessage(EXOChatKeypadPreferences.UNLOCK);
						valueBlur = 25;
						// frameBlur.setBlurRadius(valueBlur);
						llUnlock.setVisibility(View.GONE);
						llDateTime.setVisibility(View.GONE);
					} else {
						// if (EXOChatKeypadPreferences.getInstance()
						// .isEnablePasscode()) {
						// valueBlur = 1;
						// frameBlur.setBlurRadius(valueBlur);
						// }

						layoutParams.leftMargin = 0;
						rIcon.setLayoutParams(layoutParams);

					}

				}

				return true;
			}
		});

		if (EXOChatKeypadPreferences.getInstance().isFirst()) {
			tvMsg.setText(getString(R.string.first_msg));
		} else {
			if (EXOChatKeypadPreferences.getInstance().isSendMsg()) {

				if (!EXOChatKeypadPreferences.getInstance().getTextSendMsg()
						.equals("")) {
					str_msg = EXOChatKeypadPreferences.getInstance()
							.getTextSendMsg();
				} else {
					str_msg = msg[SLockscreen.indexMsg];
					SLockscreen.indexMsg++;
					if (SLockscreen.indexMsg >= msg.length) {
						SLockscreen.indexMsg = 0;
					}
				}
			} else {
				str_msg = msg[SLockscreen.indexMsg];
				SLockscreen.indexMsg++;
				if (SLockscreen.indexMsg >= msg.length) {
					SLockscreen.indexMsg = 0;
				}
			}

			tvMsg.setText(str_msg);
		}

		imgCircle = (ImageView) findViewById(R.id.imgCircle);
		imgCircle.startAnimation(aRotationCircle);

	}

	int old_x, new_x;
	int valueBlur = 1;
	LinearLayout llMsg, llUnlock;

	RelativeLayout rIcon;

	ImageView imgCircle;

	ImageView imgArrow1, imgArrow2, imgArrow3, imgArrow4, imgArrow5;
	ImageView imgBg;

	int[] droidpos;

	LinearLayout.LayoutParams layoutParams;

	int windowwidth;
	int windowheight;

	EmojiconTextView tvMsg;
	AWCircleImageView imgIcon;

	String[] msg;

	String input_passcode = "";

	String new_input = "";

	public void deletePin() {

		switch (index_pin) {
		case 2:

			btn_pin_1.setSelected(false);
			input_passcode = "";
			index_pin = 1;
			break;

		case 3:
			btn_pin_2.setSelected(false);
			index_pin = 2;
			new_input = "";
			new_input += input_passcode.charAt(0);
			input_passcode = new_input;
			break;
		case 4:
			btn_pin_3.setSelected(false);
			index_pin = 3;
			new_input = "";
			new_input += input_passcode.charAt(0);
			new_input += input_passcode.charAt(1);
			input_passcode = new_input;
			break;
		}
	}

	int type_finish = 0;

	@SuppressLint("NewApi")
	public void setPin(int value) {

		if (index_pin < 5) {
			input_passcode += value;
			// if (S5KeypadPreferences.getInstance().isSound()
			// && !S5KeypadPreferences.getInstance().isEnableSaveMode()) {
			// playTouch();
			// }
			switch (index_pin) {
			case 1:
				btn_pin_1.setSelected(true);
				break;

			case 2:
				btn_pin_2.setSelected(true);
				break;
			case 3:
				btn_pin_3.setSelected(true);
				break;
			case 4:
				btn_pin_4.setSelected(true);
				if (input_passcode.equals(EXOChatKeypadPreferences
						.getInstance().getValuePasscode())) {

					if (EXOChatKeypadPreferences.getInstance().isSound()
							&& !EXOChatKeypadPreferences.getInstance()
									.isEnableSaveMode()) {
						playUnlock();
					}

					try {
						switch (type_finish) {
						case 0:

							break;

						case 1:

							Intent intentAlarm = new Intent(
									AlarmClock.ACTION_SET_ALARM);
							startActivity(intentAlarm);

							Toast.makeText(getApplicationContext(), "Alarm",
									1000).show();
							break;
						case 2:

							ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
							PackageManager pm;
							pm = getPackageManager();
							List<PackageInfo> packs = pm
									.getInstalledPackages(0);
							for (PackageInfo pi : packs) {
								if (pi.packageName.toString().toLowerCase()
										.contains("calcul")) {
									HashMap<String, Object> map = new HashMap<String, Object>();
									map.put("appName",
											pi.applicationInfo.loadLabel(pm));
									map.put("packageName", pi.packageName);
									items.add(map);

								}
							}

							if (items.size() >= 1) {
								String packageName = (String) items.get(0).get(
										"packageName");
								Intent i = pm
										.getLaunchIntentForPackage(packageName);
								if (i != null)
									startActivity(i);
							} else {
								// Application not found
								Toast.makeText(getApplicationContext(),
										"Calculator not found", 1000).show();
							}

							break;
						case 3:
							Intent intentCall = new Intent(Intent.ACTION_DIAL,
									null); // Intent(Intent.ACTION_VIEW,ContactsContract.Contacts.CONTENT_URI);
							startActivity(intentCall);

							break;
						case 4:
							Intent intentCamera = new Intent(
									android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

							pm = mContext.getPackageManager();

							// List<ResolveInfo> list =
							// pm.queryIntentActivities(
							// i, 0);
							// System.out.println("Kai" + list.size() + "");
							// for (int t = 0; t < list.size(); t++) {
							// System.out
							// .println(list.get(t).activityInfo.packageName
							// + " "
							// + list.get(t).activityInfo.name);
							// }

							final ResolveInfo mInfo = pm.resolveActivity(
									intentCamera, 0);

							Intent intent = new Intent();
							intent.setComponent(new ComponentName(
									mInfo.activityInfo.packageName,
									mInfo.activityInfo.name));

							intent.setAction(Intent.ACTION_MAIN);
							intent.addCategory(Intent.CATEGORY_LAUNCHER);

							startActivity(intent);

							break;
						case 5:
							break;
						case 6:

							Intent sendIntent = new Intent(Intent.ACTION_MAIN);
							sendIntent.putExtra("sms_body", "text");
							sendIntent.setType("vnd.android-dir/mms-sms");
							startActivity(sendIntent);

							break;
						}

						if (EXOChatKeypadPreferences.getInstance().isVibrator()
								&& !EXOChatKeypadPreferences.getInstance()
										.isEnableSaveMode()) {
							vibrator.vibrate(300);
						}
						mHomeKeyLocker.unlock();
						SLockscreen.IS_RUN = false;
						finish();

					} catch (Exception e) {
						if (EXOChatKeypadPreferences.getInstance().isVibrator()
								&& !EXOChatKeypadPreferences.getInstance()
										.isEnableSaveMode()) {
							vibrator.vibrate(300);
						}
						mHomeKeyLocker.unlock();
						SLockscreen.IS_RUN = false;
						finish();
					}

				} else {
					if (EXOChatKeypadPreferences.getInstance().isVibrator()
							&& !EXOChatKeypadPreferences.getInstance()
									.isEnableSaveMode()) {
						vibrator.vibrate(500);
					}

					imgPasswordFail.setVisibility(View.VISIBLE);

					imgPasswordFail.startAnimation(aSetPassword);
					aSetPassword.setAnimationListener(new AnimationListener() {

						@Override
						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationEnd(Animation animation) {
							// TODO Auto-generated method stub
							input_passcode = "";
							index_pin = 1;
							btn_pin_1.setSelected(false);
							btn_pin_2.setSelected(false);
							btn_pin_3.setSelected(false);
							btn_pin_4.setSelected(false);
							imgPasswordFail.setVisibility(View.GONE);
						}
					});

				}

				// Vibrate for 500 milliseconds

				break;
			}
			index_pin++;
		}
	}

	Vibrator vibrator;

	MediaPlayer sUnlock; // , sTouch;

	private MediaPlayer startSound(String filename) {
		MediaPlayer sound = null;
		AssetFileDescriptor afd;
		try {
			afd = getAssets().openFd(filename);

			sound = new MediaPlayer();
			sound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
					afd.getLength());
			sound.prepare();
			sound.setLooping(false);

			sound.setVolume(1, 1);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return sound;
	}

	public void playUnlock() {
		sUnlock.start();
	}

	// public void playTouch() {
	// sTouch.start();
	// }

	class StateListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {

			super.onCallStateChanged(state, incomingNumber);
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				System.out.println("call Activity off hook");
				finish();

				break;
			case TelephonyManager.CALL_STATE_IDLE:
				break;
			}
		}
	};

	@Override
	public void onBackPressed() {
		// Don't allow back to dismiss.
		return;
	}

	// only used in lockdown mode
	@Override
	protected void onPause() {
		super.onPause();

		// if (!SLockscreen.IS_RUN) {
		if (mHomeKeyLocker != null) {
			mHomeKeyLocker.unlock();
		}
		// }
		handler_time.removeCallbacks(update_time);

		// Don't hang around.
		// finish();
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mHomeKeyLocker != null) {
			mHomeKeyLocker.unlock();
		}
		handler_time.removeCallbacks(update_time);
		// Don't hang around.
		// finish();
	}

	Date todayDate;
	int hour_1, hour_2, minute_1, minute_2, second_1, second_2;
	String time_str, dayOfWeek, day_of_month, month, year, dateTime;
	String AM;
	boolean isDrawAm;

	String time = "";

	String sBatteryInfo = "";
	Handler handler_time = new Handler();
	Runnable update_time = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			sBatteryInfo = "";
			if (batteryInfo.getStatus().equals("Charging")) {
				sBatteryInfo += "Charging ";
			} else if (batteryInfo.getStatus().equals("Full")) {
				sBatteryInfo += "Full ";
			}

			sBatteryInfo += batteryInfo.getLevel() + "%";
			if (batteryInfo.getLevel() < 20) {
				tvBattery.setTextColor(Color.RED);
			} else {
				tvBattery.setTextColor(Color.WHITE);
			}
			tvBattery.setText(sBatteryInfo);

			second_2++;
			if (second_2 > 9) {
				second_2 = 0;
				second_1++;

				if (second_1 == 6) {
					second_1 = 0;
					minute_2++;
					if (minute_2 > 9) {
						minute_2 = 0;
						minute_1++;
						if (minute_1 == 6) {
							minute_1 = 0;
							hour_2++;
							if (hour_2 > 9) {
								hour_2 = 0;
								hour_1++;
								// nv_hour1.setNumber(hour_1, hour_1 - 1);
							}
							if (hour_2 == 4 && hour_1 == 2) {
								hour_2 = 0;
								hour_1 = 0;
								// nv_hour1.setNumber(hour_1, 2);
							}

							if (hour_2 - 1 >= 0) {
								// nv_hour_2.setNumber(hour_2, hour_2 - 1);
							} else {
								// nv_hour_2.setNumber(hour_2, 9);
							}
						}
						if (minute_1 - 1 >= 0) {
							// nv_minute_1.setNumber(minute_1, minute_1 - 1);
						} else {
							// nv_minute_1.setNumber(minute_1, 6);
						}
					}
					if (minute_2 - 1 >= 0) {
						// nv_minute_2.setNumber(minute_2, minute_2 - 1);
					} else {
						// nv_minute_2.setNumber(minute_2, 9);
					}
				}

				// if (second_1 > 0) {
				// tvSecond1.setNumber(second_1, second_1 - 1);
				//
				// } else {
				// tvSecond1.setNumber(second_1, 6);
				// }
			}

			// if (second_2 > 0) {
			// tvSecond2.setNumber(second_2, second_2 - 1);
			// } else {
			// tvSecond2.setNumber(second_2, 9);
			// }

			time = hour_1 + "" + hour_2 + ":" + minute_1 + "" + minute_2;
			shimmerTime.setText(time);

			handler_time.postDelayed(update_time, 1000);
		}
	};

	ArrayList<NotifiItem> notifiItems;

	public String getContactName(Context context, String phoneNumber) {
		ContentResolver cr = context.getContentResolver();
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
				Uri.encode(phoneNumber));
		Cursor cursor = cr.query(uri,
				new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
		if (cursor == null) {
			return null;
		}

		String contactName = phoneNumber;
		try {
			if (cursor.moveToFirst()) {
				contactName = cursor.getString(cursor
						.getColumnIndex(PhoneLookup.DISPLAY_NAME));
			}
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		} catch (Exception ex) {
		}
		return contactName;
	}

	public int getDateDiffString(Date dateOne, Date dateTwo) {
		SimpleDateFormat dfDate = new SimpleDateFormat("dd/MM/yyyy");

		try {
			dateOne = dfDate.parse(dfDate.format(dateOne));
			dateTwo = dfDate.parse(dfDate.format(dateTwo));// Returns
															// 15/10/2012
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}

		int diffInDays = (int) ((dateTwo.getTime() - dateOne.getTime()) / (1000 * 60 * 60 * 24));

		return diffInDays;
	}

	// ArrayList<MissCallItem> missCallItems;
	Date alsoNow;
	int numMsg = 0;
	int numMissCall = 0;

	String str_msg;

	public void getNotifi() {
		alsoNow = Calendar.getInstance().getTime();
		notifiItems = new ArrayList<NotifiItem>();

		if (EXOChatKeypadPreferences.getInstance().isEnableSMS()) {
			numMsg = 0;
			Uri mSmsinboxQueryUri = Uri.parse("content://sms/inbox");
			Cursor cursor1 = getContentResolver().query(
					mSmsinboxQueryUri,
					new String[] { "_id", "thread_id", "address", "person",
							"date", "body", "type", "read", "status" }, null,
					null, null);

			String[] columns = new String[] { "address", "person", "date",
					"body", "type", "read", "status", "_id", "thread_id" };

			if (cursor1.getCount() > 0) {

				while (cursor1.moveToNext()) {

					String address = cursor1.getString(cursor1
							.getColumnIndex(columns[0]));

					String name = cursor1.getString(cursor1
							.getColumnIndex(columns[1]));

					String d = cursor1.getString(cursor1
							.getColumnIndex(columns[2]));

					Date date = new Date(cursor1.getLong(cursor1
							.getColumnIndex(columns[2])));

					String formattedDate = new SimpleDateFormat(
							"dd/MM/yyyy HH:MM").format(date);

					String msg = cursor1.getString(cursor1
							.getColumnIndex(columns[3]));
					String type = cursor1.getString(cursor1
							.getColumnIndex(columns[4]));

					String read = cursor1.getString(cursor1
							.getColumnIndex(columns[5]));

					String status = cursor1.getString(cursor1
							.getColumnIndex(columns[6]));

					String id = cursor1.getString(cursor1
							.getColumnIndex(columns[7]));

					String thread_id = cursor1.getString(cursor1
							.getColumnIndex(columns[8]));

					String nameContact;
					if (read.equals("0")) {

						if (address.contains("+")) {
							nameContact = getContactName(
									getApplicationContext(), address);

						} else {
							nameContact = address;

						}

						int diffDate = (int) getDateDiffString(date, alsoNow);

						if (EXOChatKeypadPreferences.getInstance()
								.isHideContentSms()) {
							msg = "You have new unread message";
						}
						switch (diffDate) {
						case 0:
							notifiItems.add(new NotifiItem(id, formattedDate
									.split(" ")[1] + " " + "Today",
									nameContact, msg, thread_id,
									NotifiItem.SMS, notifiItems.size()));
							break;

						case 1:
							notifiItems.add(new NotifiItem(id, formattedDate
									.split(" ")[1] + " " + "Yesterday",
									nameContact, msg, thread_id,
									NotifiItem.SMS, notifiItems.size()));
							break;
						case 2:
							notifiItems.add(new NotifiItem(id, formattedDate
									.split(" ")[1] + " " + "Two days ago",
									nameContact, msg, thread_id,
									NotifiItem.SMS, notifiItems.size()));
							break;
						default:
							notifiItems.add(new NotifiItem(id, formattedDate
									.split(" ")[1]
									+ " "
									+ formattedDate.split(" ")[0], nameContact,
									msg, thread_id, NotifiItem.SMS, notifiItems
											.size()));
							break;
						}

						numMsg++;
						// Log.d("Kai", address + " : " + nameContact + " " +
						// address);

					}
				}

				if (numMsg > 0) {
					llSMS.setVisibility(View.VISIBLE);
					lvNotifi.setVisibility(View.VISIBLE);

					tvSMS.setText(numMsg + "");
					tvSMS.startAnimation(aRotationNotifi);

				} else {

					llSMS.setVisibility(View.GONE);

				}

			}
		}

		if (EXOChatKeypadPreferences.getInstance().isEnableMissCall()) {

			numMissCall = 0;
			// missCallItems = new ArrayList<MissCallItem>();
			String callLogID, callNumber, callDate, callType, isCallNew, callName;
			final String[] projection = null;
			final String selection = null;
			final String[] selectionArgs = null;
			final String sortOrder = android.provider.CallLog.Calls.DATE
					+ " DESC";
			Cursor cursor = null;
			try {
				cursor = getApplicationContext().getContentResolver().query(
						Uri.parse("content://call_log/calls"), projection,
						selection, selectionArgs, sortOrder);
				while (cursor.moveToNext()) {
					callLogID = cursor
							.getString(cursor
									.getColumnIndex(android.provider.CallLog.Calls._ID));
					callNumber = cursor
							.getString(cursor
									.getColumnIndex(android.provider.CallLog.Calls.NUMBER));

					Date dateCall = new Date(
							cursor.getLong(cursor
									.getColumnIndex(android.provider.CallLog.Calls.DATE)));
					callDate = new SimpleDateFormat("dd/MM/yyyy HH:MM ")
							.format(dateCall);

					callType = cursor
							.getString(cursor
									.getColumnIndex(android.provider.CallLog.Calls.TYPE));
					isCallNew = cursor
							.getString(cursor
									.getColumnIndex(android.provider.CallLog.Calls.NEW));

					if (Integer.parseInt(callType) == android.provider.CallLog.Calls.MISSED_TYPE
							&& Integer.parseInt(isCallNew) > 0) {

						numMissCall++;

						int diffDate = (int) getDateDiffString(dateCall,
								alsoNow);

						// Log.d("Kai", "Call: " + diffDate);

						switch (diffDate) {
						case 0:
							callDate = callDate.split(" ")[1] + " " + "Today";
							break;
						case 1:
							callDate = callDate.split(" ")[1] + " "
									+ "Yesterday";
							break;
						case 2:
							callDate = callDate.split(" ")[1] + " "
									+ "Two days ago";
							break;
						default:
							callDate = callDate.split(" ")[1] + " "
									+ callDate.split(" ")[0];
							break;
						}

						if (!getContactName(getApplicationContext(), callNumber)
								.equals(callNumber)) {
							callName = getContactName(getApplicationContext(),
									callNumber);
						} else {
							callName = "New number";
						}
						notifiItems.add(new NotifiItem(callLogID, callDate,
								callName, callNumber, "", NotifiItem.MISS_CALL,
								notifiItems.size()));

						// .add(new MissCallItem(callLogID, getContactName(
						// getApplicationContext(), callNumber),
						// callNumber, callDate, isCallNew));
						//
						// noti
					}
				}
			} catch (Exception ex) {

			} finally {
				if (cursor != null) {
					cursor.close();
				}
			}

			if (numMissCall > 0) {
				llMissCall.setVisibility(View.VISIBLE);

				tvMissCall.setText(numMissCall + "");
				tvMissCall.startAnimation(aRotationNotifi);

				// MissCallAdapter missCallAdapter = new MissCallAdapter(
				// getApplicationContext(), missCallItems, this);
				// lvMissCall.setAdapter(missCallAdapter);
			} else {

			}

		}

		if (numMissCall > 0 || numMsg > 0) {
			lvNotifi.setVisibility(View.VISIBLE);
			// NotifiAdapter smsAdapter = new NotifiAdapter(
			// getApplicationContext(), notifiItems, this);
			//
			// SwingLeftInAnimationAdapter swingBottomInAnimationAdapter = new
			// SwingLeftInAnimationAdapter(
			// smsAdapter);
			// swingBottomInAnimationAdapter.setAbsListView(lvNotifi);
			// lvNotifi.setAdapter(swingBottomInAnimationAdapter);

			NotifiExoAdapter notifiExoAdapter = new NotifiExoAdapter(
					getApplicationContext(), notifiItems, this);
			lvNotifi.setAdapter(notifiExoAdapter);
		}

		if (numMsg == 0 && numMissCall == 0) {
			lvNotifi.setVisibility(View.GONE);
			llMissCall.setVisibility(View.GONE);
			llSMS.setVisibility(View.GONE);
		}

		if (isShowToolbar) {
			isShowToolbar = false;
			llToolbar.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		// tvMsg.setText(msg[MathuUntil.randomAm(1, msg.length)]);

		// imgIcon.startAnimation(aScaleNotifi);
		// aScaleNotifi.setAnimationListener(new AnimationListener() {
		//
		// @Override
		// public void onAnimationStart(Animation animation) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onAnimationRepeat(Animation animation) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onAnimationEnd(Animation animation) {
		// // TODO Auto-generated method stub
		// imgIcon.startAnimation(aScaleNotifi);
		// }
		// });

		getNotifi();

		aDateTime.setInterpolator(getApplicationContext(),
				android.R.anim.overshoot_interpolator);
		shimmerDate.startAnimation(aDateTime);
		shimmerTime.startAnimation(aDateTime);

		mHomeKeyLocker.lock(this);
		EXOChatKeypadPreferences.getInstance().initPreferences(
				getApplicationContext());
		batteryInfo = new BatteryInfo(getApplicationContext());
		batteryInfo.registerBatteryLevelReceiver();
		tvBattery.setText("");

		todayDate = new Date();

		int hour = todayDate.getHours();
		if (hour < 12) {
			AM = "AM";
		} else {
			AM = "PM";
		}

		switch (EXOChatKeypadPreferences.getInstance().getTimeFormat()) {
		case 0:
			isDrawAm = true;
			if (hour > 12) {
				hour = hour - 12;
			}

			break;

		case 1:
			isDrawAm = false;
			break;
		}
		int minute = todayDate.getMinutes();
		int second = todayDate.getSeconds();

		if (hour < 10) {
			time = "0" + hour;
		} else {
			time = hour + "";
		}
		time += ":";
		if (minute < 10) {
			time = time + "0" + minute;
		} else {
			time = time + minute;
		}

		second_1 = second / 10;
		// if (second_1 > 0) {
		// tvSecond1.setNumber(second_1, second_1 - 1);
		//
		// } else {
		// tvSecond1.setNumber(second_1, 6);
		// }

		// nv_second_1.setPosition(1000, 700);

		second_2 = second % 10;

		// if (second_2 > 0) {
		// tvSecond2.setNumber(second_2, second_2 - 1);
		// } else {
		// tvSecond2.setNumber(second_2, 9);
		// }
		// nv_second_2 = new NumberView();
		// nv_second_2.setFont(NumberView.roboto_thin);
		// nv_second_2.setViewSize(0.3f);
		// nv_second_2.setNumber(second_2, 0);

		// nv_second_2.setPosition(1100, 700);

		minute_1 = minute / 10;

		minute_2 = minute % 10;

		hour_1 = hour / 10;

		hour_2 = hour % 10;

		year = (1900 + todayDate.getYear()) + "";
		month = MONTH[todayDate.getMonth()];
		day_of_month = todayDate.getDate() + "";
		dayOfWeek = DAY_OF_WEEK[todayDate.getDay()];
		dateTime = dayOfWeek + ", " + day_of_month + " " + month + " " + year;
		shimmerDate.setText(dateTime);
		time = hour_1 + "" + hour_2 + ":" + minute_1 + "" + minute_2;
		shimmerTime.setText(time);

		if (EXOChatKeypadPreferences.getInstance().isDisplayTime()) {
			handler_time.postDelayed(update_time, 1000);
		}
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {

		if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
				|| (keyCode == KeyEvent.KEYCODE_POWER)
				|| (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
				|| (keyCode == KeyEvent.KEYCODE_CAMERA)) {
			// this is where I can do my stuff
			return true; // because I handled the event
		}

		if ((keyCode == KeyEvent.KEYCODE_HOME)) {

			// finish();

			return true;
		}

		return false;

	}

	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_POWER
				|| (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)
				|| (event.getKeyCode() == KeyEvent.KEYCODE_POWER)) {
			// Intent i = new Intent(this, NewActivity.class);
			// startActivity(i);
			return false;
		}
		if ((event.getKeyCode() == KeyEvent.KEYCODE_HOME)) {

			return true;
		}
		return false;
	}

	/*
	 * public void unloack(){
	 * 
	 * finish();
	 * 
	 * }
	 */
	public void onDestroy() {
		// k1.reenableKeyguard();
		if (mHomeKeyLocker != null) {
			mHomeKeyLocker.unlock();
		}
		handler_time.removeCallbacks(update_time);
		SLockscreen.IS_RUN = false;

		super.onDestroy();
	}

	public final Handler dialog = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case EXOChatKeypadPreferences.HANDLER_FINISH:

				mHomeKeyLocker.unlock();
				finish();

				break;
			case EXOChatKeypadPreferences.VIBRATE:
				if (EXOChatKeypadPreferences.getInstance().isVibrator()
						&& !EXOChatKeypadPreferences.getInstance()
								.isEnableSaveMode()) {
					vibrator.vibrate(500);
				}
				break;

			case EXOChatKeypadPreferences.UNLOCK:

				if (EXOChatKeypadPreferences.getInstance().isEnablePasscode()) {
					layoutPin.setVisibility(View.VISIBLE);
				} else {
					if (EXOChatKeypadPreferences.getInstance().isVibrator()
							&& !EXOChatKeypadPreferences.getInstance()
									.isEnableSaveMode()) {
						vibrator.vibrate(300);
					}
					mHomeKeyLocker.unlock();
					SLockscreen.IS_RUN = false;
					if (EXOChatKeypadPreferences.getInstance().isSound()
							&& !EXOChatKeypadPreferences.getInstance()
									.isEnableSaveMode()) {
						playUnlock();
					}

					finish();
				}

				// aDateTime.setInterpolator(getApplicationContext(),
				// android.R.anim.decelerate_interpolator);
				// btn0.startAnimation(aDateTime);
				// btn1.startAnimation(aDateTime);
				// btn2.startAnimation(aDateTime);
				// btn3.startAnimation(aDateTime);
				// btn4.startAnimation(aDateTime);
				// btn5.startAnimation(aDateTime);
				// btn6.startAnimation(aDateTime);
				// btn7.startAnimation(aDateTime);
				// btn8.startAnimation(aDateTime);
				// btn9.startAnimation(aDateTime);

				break;
			case EXOChatKeypadPreferences.VISIBLE:
				if (EXOChatKeypadPreferences.getInstance().isToolbar()
						&& EXOChatKeypadPreferences.getInstance()
								.isIconToolbar()) {
					imgToolBar.setVisibility(View.VISIBLE);
					imgToolBar.startAnimation(aToolbarImg);
				}
				llDateTime.setVisibility(View.VISIBLE);
				aDateTime.setInterpolator(getApplicationContext(),
						android.R.anim.overshoot_interpolator);
				shimmerDate.startAnimation(aDateTime);
				shimmerTime.startAnimation(aDateTime);

				break;
			}
		}
	};
	View mView;
	RelativeLayout unlockLayout;

	@Override
	public boolean dispatchTouchEvent(MotionEvent me) {
		this.mDetector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}

	boolean isShowToolbar;

	class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

		@Override
		public boolean onDown(MotionEvent e) {
			// TODO Auto-generated method stub

			if (EXOChatKeypadPreferences.getInstance().isToolbar()) {
				if (isShowToolbar) {
					llToolbar.startAnimation(aToolbarViewOut);
					if (EXOChatKeypadPreferences.getInstance().isIconToolbar()) {
						imgToolBar.setVisibility(View.VISIBLE);
						imgToolBar.startAnimation(aToolbarImg);
					}
					aToolbarViewOut
							.setAnimationListener(new AnimationListener() {

								@Override
								public void onAnimationStart(Animation animation) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onAnimationRepeat(
										Animation animation) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onAnimationEnd(Animation animation) {
									// TODO Auto-generated method stub
									llToolbar.setVisibility(View.GONE);
									isShowToolbar = false;
								}
							});
				}
			}
			return super.onDown(e);
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {

			if (EXOChatKeypadPreferences.getInstance().isToolbar()) {
				if (e1.getX() > e2.getX() && e1.getX() > width - 50
						&& !isShowToolbar) {
					isShowToolbar = true;
					llToolbar.setVisibility(View.VISIBLE);
					imgToolBar.clearAnimation();
					imgToolBar.setVisibility(View.GONE);
					llToolbar.startAnimation(aToolbarViewIn);

				}
			}
			return true;
		}
	}

	public int getType_finish() {
		return type_finish;
	}

	public void setType_finish(int type_finish) {
		this.type_finish = type_finish;
	}

	public void sendMessageFromToolbar() {
		layoutPin.setVisibility(View.VISIBLE);
	}

	public void startFromToolbar(int type) {

		if (EXOChatKeypadPreferences.getInstance().isSound()
				&& !EXOChatKeypadPreferences.getInstance().isEnableSaveMode()) {
			playUnlock();
		}

		try {
			switch (type) {
			case 0:

				break;

			case 1:

				Intent intentAlarm = new Intent(AlarmClock.ACTION_SET_ALARM);
				startActivity(intentAlarm);

				Toast.makeText(getApplicationContext(), "Alarm", 1000).show();
				break;
			case 2:

				ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
				PackageManager pm;
				pm = getPackageManager();
				List<PackageInfo> packs = pm.getInstalledPackages(0);
				for (PackageInfo pi : packs) {
					if (pi.packageName.toString().toLowerCase()
							.contains("calcul")) {
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("appName", pi.applicationInfo.loadLabel(pm));
						map.put("packageName", pi.packageName);
						items.add(map);

					}
				}

				if (items.size() >= 1) {
					String packageName = (String) items.get(0).get(
							"packageName");
					Intent i = pm.getLaunchIntentForPackage(packageName);
					if (i != null)
						startActivity(i);
				} else {
					// Application not found
					Toast.makeText(getApplicationContext(),
							"Calculator not found", 1000).show();
				}

				break;
			case 3:
				Intent intentCall = new Intent(Intent.ACTION_DIAL, null); // Intent(Intent.ACTION_VIEW,ContactsContract.Contacts.CONTENT_URI);
				startActivity(intentCall);

				break;
			case 4:
				Intent intentCamera = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

				pm = mContext.getPackageManager();

				final ResolveInfo mInfo = pm.resolveActivity(intentCamera, 0);

				Intent intent = new Intent();
				intent.setComponent(new ComponentName(
						mInfo.activityInfo.packageName, mInfo.activityInfo.name));

				intent.setAction(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);

				startActivity(intent);

				break;
			case 5:
				break;
			case 6:

				Intent sendIntent = new Intent(Intent.ACTION_MAIN);
				sendIntent.putExtra("sms_body", "text");
				sendIntent.setType("vnd.android-dir/mms-sms");
				startActivity(sendIntent);

				break;
			}

			if (EXOChatKeypadPreferences.getInstance().isVibrator()
					&& !EXOChatKeypadPreferences.getInstance()
							.isEnableSaveMode()) {
				vibrator.vibrate(300);
			}
			mHomeKeyLocker.unlock();
			SLockscreen.IS_RUN = false;
			finish();

		} catch (Exception e) {
			if (EXOChatKeypadPreferences.getInstance().isVibrator()
					&& !EXOChatKeypadPreferences.getInstance()
							.isEnableSaveMode()) {
				vibrator.vibrate(300);
			}
			mHomeKeyLocker.unlock();
			SLockscreen.IS_RUN = false;
			finish();
		}
	}

	public String getNetwork() {
		// Activity act = (Activity) getBaseContext();
		String network_type = "UNKNOWN";// maybe usb reverse tethering
		TelephonyManager telephonyManager = ((TelephonyManager) getApplicationContext()
				.getSystemService(Context.TELEPHONY_SERVICE));
		network_type = telephonyManager.getNetworkOperatorName();
		return network_type;
	}

	public void setFlashlight() {
		try {
			if (EXOChatKeypadPreferences.getInstance().isFlashlight()) {
				startService(new Intent(getApplicationContext(),
						ServiceFlashlight.class));

			} else {
				ServiceFlashlight.instance.turnoff_flash();
				ServiceFlashlight.instance.turnoff_camera();
				ServiceFlashlight.instance.stopSelf();
			}
		} catch (Exception ex) {
		}
	}

}
